from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsCategory, SKU
from goods.serializer import SKUsSerializer, SKUIndexSerializer, SKUHistorySerializer
from meiduo_mall.utils.pagination import StandardResultsSetPagination


class CategoriesView(APIView):
    """
        面包屑导航
    """

    def get(self, request, pk):
        try:
            cat3 = GoodsCategory.objects.get(id=pk)
        except:
            return Response({'error': '错误的分类id'})

        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })

class SKUsView(ListAPIView):

    serializer_class = SKUsSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        category_id = self.kwargs['pk']
        return SKU.objects.filter(category_id = category_id)

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer

    pagination_class = StandardResultsSetPagination


class SKUHistoryView(CreateAPIView):
    """
        保存用户浏览历史记录和获取用户浏览历史记录

    """
    serializer_class = SKUHistorySerializer
    permission_classes = (IsAuthenticated,)

    def get(self,request):
        user = request.user

        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' %user.id,0,4)

        skus = SKU.objects.filter(id__in = sku_ids)
        ser = SKUsSerializer(skus,many=True)

        return Response(ser.data)





